package com.yuan.zsschool.ui.notice;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuan.base.framework.BaseFrameworkActivity;
import com.yuan.base.framework.bean.TipResult;
import com.yuan.base.framework.http.BaseHttpCallBack;
import com.yuan.base.framework.http.BaseHttpRequest;
import com.yuan.base.framework.image.BaseImageLoad;
import com.yuan.base.utils.DialogUtil;
import com.yuan.zsschool.R;
import com.yuan.zsschool.Urls;
import com.yuan.zsschool.bean.AttachFile;
import com.yuan.zsschool.bean.Grade;
import com.yuan.zsschool.bean.School;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.StringUtils;

/**
 * 新增通告
 */
public class NoticeAddActivity extends BaseFrameworkActivity {

	private final int REQUEST_SELECT_PHOTO = 1;
	private final int REQUEST_TAKE_PHOTO = 2;
	// --------------------------控件--------------------------
	private EditText et_title;
	private EditText et_content;
	private RecyclerView rv_image;
	private TextView tv_target_school;
	private TextView tv_target_class;
	// --------------------------变量--------------------------
	private int type;
	private RecycleViewAdapter recycleViewAdapter;
	private List<AttachFile> imagePathList = new ArrayList<>();

	private List<School> schoolList;
	private List<Grade> gradeList;
	private School selectSchool;
	private String selectGrade;
	private boolean[] selectGradeFlag;

	@Override
	protected int getLayoutId() {
		return R.layout.activity_notice_add;
	}

	@Override
	protected void bindViews() {
		et_title = findViewById(R.id.et_title);
		et_content = findViewById(R.id.et_content);
		rv_image = findViewById(R.id.rv_image);
		tv_target_school = findViewById(R.id.tv_target_school);
		tv_target_class = findViewById(R.id.tv_target_class);
		setOnClickListener(R.id.ll_add_img, v -> {
			String[] items = {"拍照", "从相册中选择"};
			DialogUtil.select(this, "请选择图片来源", items, (dialog, which) -> {
				switch (which) {
					case 0:
						// 拍照
						GalleryFinal.openCamera(REQUEST_SELECT_PHOTO, new FunctionConfig.Builder().build(), onHanlderResultCallback);
						break;
					case 1:
						// 本地选取
						GalleryFinal.openGallerySingle(REQUEST_SELECT_PHOTO, new FunctionConfig.Builder().build(), onHanlderResultCallback);
						break;
				}
			}, "取消", null);
		});
		setOnClickListener(R.id.btn_submit, v -> {
			doSubmit();
		});
		setOnClickListener(R.id.ll_target_school, v -> {
			if (gradeList == null) {
				BaseHttpRequest.get(Urls.getUrl(Urls.getAllSchool), new BaseHttpCallBack<JSONObject>() {
					@Override
					public void onPost() {
						hideProgressBar();
					}

					@Override
					public void onPreStart() {
						showProgressBar("正在加载数据");
					}

					@Override
					public void onSuccess(JSONObject result) {
						schoolList = JSON.parseArray(result.getString("content"), School.class);
						showSelectSchool(schoolList);
					}
				});
			} else {
				showSelectSchool(schoolList);
			}
		});

		setOnClickListener(R.id.ll_target_class, v -> {
			if (selectSchool == null) {
				showToast("请先选择学校");
				return;
			}
			if (gradeList == null) {
				HashMap<String, Object> params = new HashMap<>();
				params.put("school", selectSchool.getId());
				BaseHttpRequest.get(Urls.getUrl(Urls.getGradeById), params, new BaseHttpCallBack<JSONObject>() {
					@Override
					public void onPost() {
						hideProgressBar();
					}

					@Override
					public void onPreStart() {
						showProgressBar("正在加载数据");
					}

					@Override
					public void onSuccess(JSONObject result) {
						gradeList = JSON.parseArray(result.getString("content"), Grade.class);
						showSelectClass(gradeList);
					}
				});
			} else {
				showSelectClass(gradeList);
			}
		});
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		type = getIntent().getIntExtra("type", -1);
		if (type == -1) {
			showToast("发生错误");
			closeSelf();
		}
		recycleViewAdapter = new RecycleViewAdapter();
		rv_image.setLayoutManager(new GridLayoutManager(this, 3));
		rv_image.setAdapter(recycleViewAdapter);
		ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
			@Override
			public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
				int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;//拖拽
				int swipeFlags = 0;//侧滑删除
				return makeMovementFlags(dragFlags, swipeFlags);
			}

			@Override
			public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
				//滑动事件
				Collections.swap(imagePathList, viewHolder.getAdapterPosition(), target.getAdapterPosition());
				recycleViewAdapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
				new Handler().postDelayed(() -> recycleViewAdapter.notifyDataSetChanged(), 500);
				return false;
			}

			@Override
			public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
			}

			@Override
			public boolean isLongPressDragEnabled() {
				//是否可拖拽
				return true;
			}
		});
		helper.attachToRecyclerView(rv_image);

//		CacheManager.getInstance().
	}

	private void doSubmit() {
		if (TextUtils.isEmpty(getStringByUI(et_title))) {
			showToast("请输入标题");
			return;
		}
		if (TextUtils.isEmpty(getStringByUI(et_content))) {
			showToast("请输入内容");
			return;
		}
		if (TextUtils.isEmpty(selectGrade)) {
			showToast("请选择发布班级");
			return;
		}
		String[] pics = new String[imagePathList.size()];
		for (int i = 0; i < imagePathList.size(); i++) {
			pics[i] = imagePathList.get(i).getName();
		}
		HashMap<String, Object> params = new HashMap<>();
		params.put("type", type);
		params.put("title", getStringByUI(et_title));
		params.put("content", getStringByUI(et_content));
		params.put("targetGrades", selectGrade);
		params.put("pics", pics);
		BaseHttpRequest.post(Urls.getUrl(Urls.addNotification), params, new BaseHttpCallBack<TipResult>() {
			@Override
			public void onPost() {
				hideProgressBarAtOnce();
			}

			@Override
			public void onPreStart() {
				showProgressBar("正在提交...");
			}

			@Override
			public void onSuccess(TipResult result) {
				if (result.isSuccess()) {
					showToast("发布成功");
					closeSelf();
				} else {
					showToast(result.getMessage());
				}
			}
		});
	}

	private void showSelectSchool(List<School> schoolList) {
		String[] schools = new String[schoolList.size()];
		for (int i = 0; i < schoolList.size(); i++) {
			schools[i] = schoolList.get(i).getName();
		}
		DialogUtil.select(this, "选择学校", schools, (dialog, which) -> {
			tv_target_school.setText(schools[which]);
			selectSchool = schoolList.get(which);
			gradeList = null;
			tv_target_class.setText("");
			selectGrade = "";
			selectGradeFlag = null;
		});
	}

	private void showSelectClass(List<Grade> gradeList) {
		String[] schools = new String[gradeList.size()];
		if (selectGradeFlag == null) {
			selectGradeFlag = new boolean[gradeList.size()];
			for (int i = 0; i < gradeList.size(); i++) {
				selectGradeFlag[i] = false;
			}
		}
		for (int i = 0; i < gradeList.size(); i++) {
			schools[i] = gradeList.get(i).getName();
		}
		DialogUtil.selectMulti(this, "选择班级", schools, selectGradeFlag, null, "确定", (dialog, which) -> {
			selectGrade = "";
			String temp = "";
			for (int i = 0; i < selectGradeFlag.length; i++) {
				if (selectGradeFlag[i]) {
					selectGrade += gradeList.get(i).getId() + ",";
					temp += gradeList.get(i).getName() + ",";
				}
			}
			if (selectGrade.length() > 0) {
				selectGrade = selectGrade.substring(0, selectGrade.length() - 1);
				temp = temp.substring(0, temp.length() - 1);
			}
			tv_target_class.setText(temp);
		}, "取消", null);
	}


	private GalleryFinal.OnHanlderResultCallback onHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
		@Override
		public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
			switch (reqeustCode) {
				case REQUEST_SELECT_PHOTO:
				case REQUEST_TAKE_PHOTO:
					upImg(resultList.get(0).getPhotoPath());
					break;
			}
		}

		@Override
		public void onHanlderFailure(int requestCode, String errorMsg) {
//			showToast("图片选择出错");
		}
	};

	private void upImg(String filePath) {
//		AttachFile attachFile = new AttachFile();
//		attachFile.setLocalPath(filePath);
//		imagePathList.add(attachFile);
//		recycleViewAdapter.notifyDataSetChanged();
		submitImage(filePath, this, result -> {
			AttachFile attachFile = new AttachFile();
			attachFile.setLocalPath(filePath);
			attachFile.setName(result);
			imagePathList.add(attachFile);
			recycleViewAdapter.notifyDataSetChanged();
		});
	}


	private ProgressDialog mProgressDialog;

	public void submitImage(final String path, final BaseFrameworkActivity activity, final UploadSuccess onSuccess) {
		File file = new File(path);
		BaseHttpRequest.post(Urls.getUrl(Urls.upload), file, new BaseHttpCallBack<TipResult>() {
			@Override
			public void onLoading(long current, long total) {
				mProgressDialog.setProgress((int) (((float) current / (float) total) * 100));
			}

			@Override
			public void onPreStart() {
				mProgressDialog = new ProgressDialog(activity);
				mProgressDialog.setTitle("正在上传...");
				mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				mProgressDialog.setMax(100);
				mProgressDialog.setCanceledOnTouchOutside(false);
				mProgressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
					if (getCancelable() != null) {
						getCancelable().cancel();
					}
				});
				mProgressDialog.show();
			}

			@Override
			public void onSuccess(TipResult result) {
				try {
					mProgressDialog.dismiss();
				} catch (Exception ignored) {
				}
				if (StringUtils.isEmpty(result.getMessage())) {
					activity.showToast("上传失败,请重试");
				} else {
					onSuccess.onSuccess(result.getMessage());
				}
			}

			@Override
			public void onFailure(int code, String msg) {
				activity.showToast("上传失败,请重试");
				try {
					mProgressDialog.dismiss();
				} catch (Exception ignored) {
				}
			}

			@Override
			public void onPost() {
				mProgressDialog = null;
			}
		});
	}

	public interface UploadSuccess {
		void onSuccess(String fileId);
	}


	public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.MyViewHolder> {

		@NonNull
		@Override
		public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
			View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_notice_add_image, parent, false);
			return new MyViewHolder(view);
		}

		@Override
		public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
			AttachFile path = imagePathList.get(position);
			BaseImageLoad.loadLocal(path.getLocalPath(), holder.iv_img);
			holder.iv_remove.setOnClickListener(v -> {
				imagePathList.remove(position);
				notifyDataSetChanged();
			});
		}

		@Override
		public int getItemCount() {
			return imagePathList.size();
		}

		class MyViewHolder extends RecyclerView.ViewHolder {
			private ImageView iv_img;
			private ImageView iv_remove;

			MyViewHolder(View itemView) {
				super(itemView);
				iv_img = itemView.findViewById(R.id.iv_img);
				iv_remove = itemView.findViewById(R.id.iv_remove);
			}
		}
	}


}

